"""
筹码峰分析模块
专业的筹码分布和成本分析
"""

import pandas as pd
import numpy as np
from typing import Dict, List, Tuple


class ChipAnalyzer:
    """筹码峰分析类"""
    
    @staticmethod
    def calculate_chip_distribution(df: pd.DataFrame, lookback_days: int = 90) -> Dict:
        """
        计算筹码分布
        基于成交量加权的价格分布
        """
        if len(df) < 20:
            return {}
        
        # 取最近N天的数据
        recent_data = df.tail(lookback_days) if len(df) >= lookback_days else df
        
        result = {}
        current_price = df.iloc[-1]['收盘']
        
        # 计算成交量加权平均价格
        total_volume = recent_data['成交量'].sum()
        if total_volume == 0:
            return result
        
        # 成交量加权平均成本
        vwap = (recent_data['收盘'] * recent_data['成交量']).sum() / total_volume
        
        result['筹码平均成本'] = f"¥{vwap:.2f}"
        result['当前价格'] = f"¥{current_price:.2f}"
        
        # 计算盈亏比例
        profit_loss_ratio = (current_price - vwap) / vwap * 100
        result['成本乖离率'] = f"{profit_loss_ratio:+.2f}%"
        
        if profit_loss_ratio > 10:
            result['获利盘状态'] = "大量获利盘"
            result['获利盘评价'] = "⚠️ 获利盘较多，注意回调风险"
        elif profit_loss_ratio > 5:
            result['获利盘状态'] = "适中获利盘"
            result['获利盘评价'] = "📊 获利盘适中"
        elif profit_loss_ratio > -5:
            result['获利盘状态'] = "盈亏平衡"
            result['获利盘评价'] = "✅ 筹码基本平衡"
        elif profit_loss_ratio > -10:
            result['获利盘状态'] = "轻度套牢"
            result['获利盘评价'] = "💎 部分套牢盘"
        else:
            result['获利盘状态'] = "严重套牢"
            result['获利盘评价'] = "💎💎 大量套牢盘，可能存在反弹机会"
        
        return result
    
    @staticmethod
    def calculate_chip_concentration(df: pd.DataFrame, bins: int = 20) -> Dict:
        """
        计算筹码集中度
        分析筹码的集中程度
        """
        if len(df) < 30:
            return {}
        
        recent_data = df.tail(90) if len(df) >= 90 else df
        
        # 创建价格区间
        price_min = recent_data['最低'].min()
        price_max = recent_data['最高'].max()
        price_bins = np.linspace(price_min, price_max, bins + 1)
        
        # 计算每个价格区间的成交量
        volume_distribution = []
        for i in range(len(price_bins) - 1):
            bin_low = price_bins[i]
            bin_high = price_bins[i + 1]
            
            # 找出在这个价格区间内的数据
            mask = (recent_data['收盘'] >= bin_low) & (recent_data['收盘'] < bin_high)
            bin_volume = recent_data.loc[mask, '成交量'].sum()
            
            if bin_volume > 0:
                volume_distribution.append({
                    'price_low': bin_low,
                    'price_high': bin_high,
                    'price_mid': (bin_low + bin_high) / 2,
                    'volume': bin_volume
                })
        
        if not volume_distribution:
            return {}
        
        # 找出成交量最大的区间（主峰）
        volume_distribution.sort(key=lambda x: x['volume'], reverse=True)
        main_peak = volume_distribution[0]
        
        result = {}
        result['主力成本区间'] = f"¥{main_peak['price_low']:.2f} - ¥{main_peak['price_high']:.2f}"
        result['主力成本中枢'] = f"¥{main_peak['price_mid']:.2f}"
        
        total_volume = sum(item['volume'] for item in volume_distribution)
        main_peak_ratio = main_peak['volume'] / total_volume * 100
        result['主峰集中度'] = f"{main_peak_ratio:.2f}%"
        
        # 判断筹码集中度
        if main_peak_ratio > 40:
            result['集中度评价'] = "高度集中"
            result['集中度信号'] = "🔥 筹码高度集中，主力控盘明显"
        elif main_peak_ratio > 30:
            result['集中度评价'] = "较为集中"
            result['集中度信号'] = "✅ 筹码较为集中，有主力迹象"
        elif main_peak_ratio > 20:
            result['集中度评价'] = "一般集中"
            result['集中度信号'] = "📊 筹码集中度一般"
        else:
            result['集中度评价'] = "分散"
            result['集中度信号'] = "⚠️ 筹码较为分散，换手充分"
        
        # 当前价格与主力成本关系
        current_price = df.iloc[-1]['收盘']
        distance_to_peak = (current_price - main_peak['price_mid']) / main_peak['price_mid'] * 100
        
        result['价格距主力成本'] = f"{distance_to_peak:+.2f}%"
        
        if distance_to_peak > 15:
            result['相对位置'] = "远高于主力成本"
            result['位置评价'] = "⚠️ 价格已大幅偏离成本区，注意风险"
        elif distance_to_peak > 5:
            result['相对位置'] = "高于主力成本"
            result['位置评价'] = "📊 价格在成本区上方，获利盘较多"
        elif distance_to_peak > -5:
            result['相对位置'] = "接近主力成本"
            result['位置评价'] = "✅ 价格在主力成本区附近"
        elif distance_to_peak > -15:
            result['相对位置'] = "低于主力成本"
            result['位置评价'] = "💎 价格在成本区下方，套牢盘较多"
        else:
            result['相对位置'] = "远低于主力成本"
            result['位置评价'] = "💎💎 价格大幅低于成本，深度套牢"
        
        # 次峰分析
        if len(volume_distribution) > 1:
            second_peak = volume_distribution[1]
            second_peak_ratio = second_peak['volume'] / total_volume * 100
            
            if second_peak_ratio > 20:
                result['双峰结构'] = "是"
                result['次峰位置'] = f"¥{second_peak['price_mid']:.2f}"
                result['次峰评价'] = "📊 存在明显双峰结构"
        
        return result
    
    @staticmethod
    def analyze_chip_migration(df: pd.DataFrame) -> Dict:
        """
        分析筹码移动
        比较短期和长期的筹码分布变化
        """
        if len(df) < 60:
            return {}
        
        result = {}
        
        # 短期筹码成本（30天）
        short_term_data = df.tail(30)
        short_term_cost = (short_term_data['收盘'] * short_term_data['成交量']).sum() / short_term_data['成交量'].sum()
        
        # 长期筹码成本（90天）
        long_term_data = df.tail(90) if len(df) >= 90 else df.tail(60)
        long_term_cost = (long_term_data['收盘'] * long_term_data['成交量']).sum() / long_term_data['成交量'].sum()
        
        result['短期筹码成本'] = f"¥{short_term_cost:.2f}"
        result['长期筹码成本'] = f"¥{long_term_cost:.2f}"
        
        # 筹码移动方向
        cost_change = (short_term_cost - long_term_cost) / long_term_cost * 100
        result['成本变化'] = f"{cost_change:+.2f}%"
        
        if cost_change > 5:
            result['筹码移动'] = "向上移动"
            result['移动评价'] = "🚀 筹码快速上移，主力吸筹明显"
            result['移动信号'] = "bullish"
        elif cost_change > 2:
            result['筹码移动'] = "缓慢上移"
            result['移动评价'] = "✅ 筹码温和上移，稳健上涨"
            result['移动信号'] = "mild_bullish"
        elif cost_change > -2:
            result['筹码移动'] = "基本稳定"
            result['移动评价'] = "📊 筹码稳定，横盘整理"
            result['移动信号'] = "neutral"
        elif cost_change > -5:
            result['筹码移动'] = "缓慢下移"
            result['移动评价'] = "⚠️ 筹码下移，获利盘出逃"
            result['移动信号'] = "mild_bearish"
        else:
            result['筹码移动'] = "快速下移"
            result['移动评价'] = "❌ 筹码快速下移，主力派发"
            result['移动信号'] = "bearish"
        
        # 换手率分析
        recent_turnover = short_term_data['换手率'].mean() if '换手率' in short_term_data.columns else 0
        if recent_turnover > 0:
            result['近期换手率'] = f"{recent_turnover:.2f}%"
            
            if recent_turnover > 10:
                result['换手评价'] = "🔥 换手率极高，筹码快速流转"
            elif recent_turnover > 5:
                result['换手评价'] = "✅ 换手率较高，交投活跃"
            elif recent_turnover > 2:
                result['换手评价'] = "📊 换手率正常"
            else:
                result['换手评价'] = "⚠️ 换手率较低，筹码稳定"
        
        return result
    
    @staticmethod
    def calculate_chip_score(df: pd.DataFrame) -> Tuple[float, List[str]]:
        """
        基于筹码分析计算评分
        """
        if len(df) < 30:
            return 50.0, ["数据不足"]
        
        score = 50
        signals = []
        
        # 筹码分布分析
        distribution = ChipAnalyzer.calculate_chip_distribution(df)
        if '成本乖离率' in distribution:
            ratio_str = distribution['成本乖离率'].rstrip('%')
            ratio = float(ratio_str)
            
            if -5 < ratio < 5:
                score += 10
                signals.append("✅ 价格接近筹码成本区")
            elif ratio < -10:
                score += 15
                signals.append("💎 价格远低于成本，深度超卖")
            elif ratio > 10:
                score -= 10
                signals.append("⚠️ 价格远高于成本，获利盘多")
        
        # 筹码集中度分析
        concentration = ChipAnalyzer.calculate_chip_concentration(df)
        if '集中度评价' in concentration:
            if concentration['集中度评价'] in ['高度集中', '较为集中']:
                score += 10
                signals.append("🔥 筹码高度集中，主力控盘")
        
        # 筹码移动分析
        migration = ChipAnalyzer.analyze_chip_migration(df)
        if '移动信号' in migration:
            signal = migration['移动信号']
            if signal == 'bullish':
                score += 15
                signals.append("🚀 筹码快速上移")
            elif signal == 'mild_bullish':
                score += 10
                signals.append("✅ 筹码温和上移")
            elif signal == 'bearish':
                score -= 15
                signals.append("❌ 筹码快速下移")
            elif signal == 'mild_bearish':
                score -= 10
                signals.append("⚠️ 筹码缓慢下移")
        
        final_score = max(0, min(100, score))
        return final_score, signals

